﻿#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.IO;

namespace MagicLib
{
    public class SkipSplashEditor
    {
        private const string MENU_PATH = "MagicLib/Skip Splash Screen";
        private const string SETTINGS_PATH = "Assets/Resources/SkipSplashSettings.asset";
        private const string RESOURCES_DIR = "Assets/Resources";

        [MenuItem(MENU_PATH, priority = 1)]
        private static void ToggleSkipSplash()
        {
            // 确保设置资源存在
            var settings = GetOrCreateSettings();
            
            // 切换状态
            settings.enableSkipSplash = !settings.enableSkipSplash;
            EditorUtility.SetDirty(settings);
            AssetDatabase.SaveAssets();
            
            Debug.Log($"[SkipSplash] 功能已{(settings.enableSkipSplash ? "启用" : "禁用")}");
        }

        [MenuItem(MENU_PATH, true)]
        private static bool ToggleSkipSplashValidate()
        {
            var settings = GetOrCreateSettings();
            Menu.SetChecked(MENU_PATH, settings.enableSkipSplash);
            return true;
        }

        private static SkipSplashSettings GetOrCreateSettings()
        {
            var settings = AssetDatabase.LoadAssetAtPath<SkipSplashSettings>(SETTINGS_PATH);
            
            if (settings == null)
            {
                // 创建资源目录
                if (!Directory.Exists(RESOURCES_DIR))
                {
                    Directory.CreateDirectory(RESOURCES_DIR);
                    AssetDatabase.Refresh();
                }
                
                // 创建新设置
                settings = ScriptableObject.CreateInstance<SkipSplashSettings>();
                AssetDatabase.CreateAsset(settings, SETTINGS_PATH);
                AssetDatabase.SaveAssets();
            }
            
            return settings;
        }
        
        // 注册构建处理器
        [InitializeOnLoadMethod]
        private static void RegisterBuildHandler()
        {
            BuildPlayerWindow.RegisterBuildPlayerHandler(BuildPlayerHandler);
        }
        
        private static void BuildPlayerHandler(BuildPlayerOptions options)
        {
            // 确保设置资源存在并包含在构建中
            GetOrCreateSettings();
            
            // 继续构建流程
            BuildPipeline.BuildPlayer(options);
        }
    }
}
#endif